<?php
namespace app\models;
/**
 * @desc 类目操作model
 */
use Yii;
use app\models\BaseModel;
use app\enum\EnumOther;
use app\dao\CategoryDAO;
use app\helpers\storeTokenTool;
use app\helpers\Curl;

class CategoryModel extends BaseModel
{
	/**
	 * @desc覆盖父方法返回对象
	 * @author liaojianwen
	 * @date 2016-12-01
	 * @return CategoryModel
	 */
	public static function model($className = __CLASS__)
	{
		return parent::model($className);
	}
	
	/**
	 * @desc 获取类目书
	 * @author liaojianwen
	 * @date 2016-12-08
	 */
	public function getCategorys($pcid, $selectId = 0, $isDel = 0)
	{
		$result  = CategoryDAO::getInstance()->getCatTreeByPcid($pcid,$selectId);
		if(empty($result)){
			return false;
		}
		return $result;
	}
	
	
	/**
	 * @desc 获取类目列表
	 * @author liaojianwen
	 * @date 2016-12-08
	 */
	public function getCategoryList()
	{
		$result = CategoryDAO::getInstance()->getCategoryList();
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		array_push($result, ['id'=>0,'pId'=>-1,'name'=>"根目录",'open'=>true]);
		return $result;
	}
	
	/**
	 * @desc 获取类目信息
	 * @author liaojianwen
	 * @date 2016-12-2
	 */
	public function getCateInfo($id)
	{
		if(empty($id)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$result = CategoryDAO::getInstance()->getCateInfo($id);
		if(empty($result)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','no data found');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,$result);
		
	}
	
	/**
	 * @desc 保存类目
	 * @author liaojianwen
	 * @date 2016-12-02
	 */
	public function saveCate($cateInfo)
	{
		if(empty($cateInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$tr = Yii::$app->db->beginTransaction();
		try{
			foreach($cateInfo as $key => $cate){
				if(empty($cate)){
					unset($cateInfo[$key]);
				}
			}
			if(isset($cateInfo['parent_id'])){
				$res_count = CategoryDAO::getInstance()->iselect("category_id", "category_id =:id", [':id'=>$cateInfo['parent_id']],'one');
				if(empty($res_count)){
					$tr->rollBack();
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','parent is not exist');
				}
			}
			$conditions = "category_id =:id and delete_flag = :flag";
			$params=[
					':id'=>(isset($cateInfo['category_id'])?$cateInfo['category_id']:0),
					':flag'=> EnumOther::NO_DELETE,
			];
			$result = CategoryDAO::getInstance()->ireplaceinto($cateInfo, $conditions, $params,true);
			if(!$result){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','save fail');
			}
			// 同步供应链到店铺
			$res_cate = $this->syncStoreCategory($result);
			if($res_cate != 'true'){
				$tr->rollBack();
				return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', 'store category sync fail');
			}
			$tr->commit();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		}catch (\Exception $e){
			$tr->rollBack();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
		}
		
	}
	
	/**
	 * @desc 删除类目信息
	 * @param int $id 
	 * @author liaojianwen
	 * @date 2016-12-05
	 */
	public function delCate($id)
	{
		if (empty ( $id )) {
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$columns = [
			'delete_flag'=>EnumOther::DELETED,
		];
		$conditions = "category_id = :id or parent_id = :pid";
		$params = [
			':id'=> $id,
			':pid'=> $id,
		];
		
		$result = CategoryDAO::getInstance()->iupdate($columns, $conditions, $params);
		if(!$result){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','del fail');
		}
		return $this->handleApiFormat(EnumOther::ACK_SUCCESS,'');
	}
	
	/**
	 * @desc 商城新增类目同步更新到scm
	 * @author liaojianwen
	 * @date 2017-03-21
	 */
	public function shopInsertCategory($categoryInfo)
	{
		$cateInfo = isset($categoryInfo['data'])? $categoryInfo['data'] :'';
		if(empty($cateInfo)){
			return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','param is empty');
		}
		$tr = Yii::$app->db->beginTransaction();
		try{
			foreach($cateInfo as $key => $cate){
				if(empty($cate)){
					unset($cateInfo[$key]);
				}
			}
			if(isset($cateInfo['parent_id'])){
				$res_count = CategoryDAO::getInstance()->iselect("category_id", "category_id =:id", [':id'=>$cateInfo['parent_id']],'one');
				if(empty($res_count)){
					return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','parent is not exist');
				}
			}
			$columns = [
				'category_name'=> $cateInfo['cat_name'],
				'parent_id' => $cateInfo['parent_id'],
				'shop_cat_id' => $cateInfo['cat_id'],
			];
			$conditions = "shop_cat_id =:id and delete_flag = :flag";
			$params=[
					':id'=>(isset($cateInfo['cat_id'])?$cateInfo['cat_id']:0),
					':flag'=> EnumOther::NO_DELETE,
			];
			$result = CategoryDAO::getInstance()->ireplaceinto($columns, $conditions, $params);
			if(!$result){
				return $this->handleApiFormat(EnumOther::ACK_FAILURE,'','save fail');
			}
			$tr->commit();
			return $this->handleApiFormat ( EnumOther::ACK_SUCCESS, '' );
		} catch (\Exception $e){
			$tr->rollBack();
			return $this->handleApiFormat(EnumOther::ACK_FAILURE, '', $e->getMessage());
		}
	}
	
	/**
	 * @desc 类目同步到店铺
	 * @author liaojianwen
	 * @date 2017-08-03
	 */
	public function syncStoreCategory($category_id)
	{
		if(!$category_id){
			return false;
		}
		try{
			$cate_fields =[
				'category_id',
				'category_name',
				'parent_id',
				'create_time',
				'remark',
			];
			$conditions="category_id=:cid";
			$params= [
				':cid'=>$category_id
			];
			$cate_select = CategoryDAO::getInstance()->iselect($cate_fields, $conditions, $params,'one');
			if(!$cate_select){
				return false;
			}
			$storeUrl = Yii::$app->params ['storeUrl'];
				
			$key = storeTokenTool::getInstance()->getToken();
			$url = "{$storeUrl}/scm/api/category-update";
				
			$postdata = json_encode($cate_select);
			$result = Curl::curlOption($url, 'POST', $postdata, $key);
			return  $result;
			
		} catch (\Exception $e){
			return false;
		}
		
	}
}